document.addEventListener('DOMContentLoaded', function () {
    // 初始化页面
    initAdminPage();

    // 注销按钮点击事件
    document.getElementById('logoutBtn').addEventListener('click', logout);

    // 商品管理点击事件
    document.getElementById('productManagement').addEventListener('click', function () {
        showSection('productManagement');
    });

    // 留言管理点击事件
    document.getElementById('messageManagement').addEventListener('click', function () {
        showSection('messageManagement');
    });

    // 添加商品按钮点击事件
    document.getElementById('addProductBtn').addEventListener('click', function () {
        showAddProductModal();
    });

    // 关闭模态框
    document.querySelector('.close').addEventListener('click', function () {
        closeModal();
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === document.getElementById('addProductModal') || event.target === document.getElementById('editProductModal')) {
            closeModal();
        }
    });
});

function initAdminPage() {
    // 默认显示商品管理页面
    showSection('productManagement');

    // 加载分类数据用于商品添加和编辑
    loadCategories();
}

function showSection(sectionId) {
    // 隐藏所有内容区域
    document.getElementById('productManagementContent').classList.add('hidden');
    document.getElementById('messageManagementContent').classList.add('hidden');

    // 移除活动状态
    document.querySelectorAll('.admin-sidebar a').forEach(function (link) {
        link.classList.remove('active');
    });

    // 显示对应的内容区域
    if (sectionId === 'productManagement') {
        document.getElementById('productManagementContent').classList.remove('hidden');
        document.getElementById('productManagement').classList.add('active');
        fetchProducts();
    } else if (sectionId === 'messageManagement') {
        document.getElementById('messageManagementContent').classList.remove('hidden');
        document.getElementById('messageManagement').classList.add('active');
        fetchMessages();
    }
}

function loadCategories() {
    // 获取分类数据
    fetch('/api/categories')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取分类失败');
            }
            return response.json();
        })
        .then(categories => {
            // 填充添加商品模态框的分类下拉列表
            const addProductCategory = document.getElementById('productCategory');
            addProductCategory.innerHTML = '';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                addProductCategory.appendChild(option);
            });

            // 填充编辑商品模态框的分类下拉列表
            const editProductCategory = document.getElementById('editProductCategory');
            editProductCategory.innerHTML = '';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                editProductCategory.appendChild(option);
            });
        })
        .catch(error => {
            console.error('获取分类出错:', error);
        });
}

function fetchProducts() {
    // 获取商品列表
    fetch('/api/products')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(products => {
            const productList = document.getElementById('productList');
            productList.innerHTML = '';

            if (products.length === 0) {
                productList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无商品</p>';
                return;
            }

            products.forEach(product => {
                const productCard = document.createElement('div');
                productCard.className = 'product-card';

                productCard.innerHTML = `
                    <h3>${product.name}</h3>
                    <p>价格: ¥${product.price.toFixed(2)}</p>
                    <p>库存: ${product.stock}</p>
                    <p>分类: ${product.category.name}</p>
                    <div class="product-actions-btn">
                        <button class="edit-btn" data-id="${product.id}">编辑</button>
                        <button class="delete-btn" data-id="${product.id}">删除</button>
                    </div>
                `;

                // 编辑按钮点击事件
                const editBtn = productCard.querySelector('.edit-btn');
                editBtn.addEventListener('click', function () {
                    showEditProductModal(product.id);
                });

                // 删除按钮点击事件
                const deleteBtn = productCard.querySelector('.delete-btn');
                deleteBtn.addEventListener('click', function () {
                    deleteProduct(product.id);
                });

                productList.appendChild(productCard);
            });
        })
        .catch(error => {
            console.error('获取商品出错:', error);
        });
}

function showAddProductModal() {
    // 显示添加商品模态框
    document.getElementById('addProductModal').style.display = 'block';
    document.getElementById('addProductForm').reset();
}

function showEditProductModal(productId) {
    // 获取商品详情
    fetch(`/api/products/${productId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(product => {
            // 填充表单数据
            document.getElementById('editProductId').value = product.id;
            document.getElementById('editProductName').value = product.name;
            document.getElementById('editProductPrice').value = product.price;
            document.getElementById('editProductStock').value = product.stock;
            document.getElementById('editProductDescription').value = product.description;

            // 设置分类
            const editProductCategory = document.getElementById('editProductCategory');
            editProductCategory.value = product.category.id;

            // 显示编辑商品模态框
            document.getElementById('editProductModal').classList.remove('hidden');
        })
        .catch(error => {
            console.error('获取商品出错:', error);
        });
}

function closeModal() {
    // 关闭所有模态框
    document.getElementById('addProductModal').style.display = 'none';
    document.getElementById('editProductModal').classList.add('hidden');
}

function logout() {
    // 注销登录
    localStorage.removeItem('token');
    localStorage.removeItem('userType');
    window.location.href = '/login.html';
}

function deleteProduct(productId) {
    if (confirm('确定要删除该商品吗?')) {
        fetch(`/api/products/${productId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('删除商品失败');
                }
                return response.json();
            })
            .then(data => {
                console.log('商品删除成功:', data);
                fetchProducts(); // 重新加载商品列表
            })
            .catch(error => {
                console.error('删除商品出错:', error);
            });
    }
}

function fetchMessages() {
    // 获取买家留言
    fetch('/api/messages')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取留言失败');
            }
            return response.json();
        })
        .then(messages => {
            const messageList = document.getElementById('messageList');
            messageList.innerHTML = '';

            if (messages.length === 0) {
                messageList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无留言</p>';
                return;
            }

            messages.forEach(message => {
                const messageCard = document.createElement('div');
                messageCard.className = 'message-card';

                messageCard.innerHTML = `
                    <h3>${message.user.username} 的留言</h3>
                    <p>留言内容: ${message.content}</p>
                    <p>留言时间: ${new Date(message.createdAt).toLocaleString()}</p>
                    <p>回复: ${message.reply || '暂无回复'}</p>
                `;

                messageList.appendChild(messageCard);
            });
        })
        .catch(error => {
            console.error('获取留言出错:', error);
        });
}